import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import MentorRecommand from '../views/MentorRecommand.vue'
import MentorSearch from '../views/MentorSearch.vue'
import MySpace from "../views/MySpace.vue";
import Register from '../views/Register.vue'
import HomeView from '../views/HomeView.vue'
import TeacherDetail from '@/views/TeacherDetail.vue'
import ContactUs from '@/views/contactUs.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: {
      showHeader: true
    }
  }, {
    path: '/login',
    name: 'login',
    component: Login,
    meta: {
      showHeader: false
    }
  }, {
    path: '/register',
    name: 'register',
    component: Register,
    meta: {
      showHeader: false
    }
  }, {
    path: '/recommand',
    name: 'recommand',
    component: MentorRecommand,
    meta: {
      showHeader: true
    }
  }, {
    path: '/search',
    name: 'search',
    component: MentorSearch,
    meta: {
      showHeader: true
    }
  }, {
    path: '/myspace',
    name: 'myspace',
    component: MySpace,
    meta: {
      showHeader: true
    }
  }, {
    path: '/teacherDetail',
    name: 'teacherDetail',
    component: TeacherDetail,
    meta: {
      showHeader: true
    }
  }, {
    path: '/contactUs',
    name: 'contactUs',
    component: ContactUs,
    meta: {
      showHeader: true
    }
  }
]
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {

  // 检查 sessionStorage 中的登录状态  
  const loginStatus = sessionStorage.getItem('loginCookie');

  if (!loginStatus) {
    // 如果用户未登录，且目标路由不是登录页，则重定向到登录页  
    if (to.path !== '/login' && to.path!== '/register') {
      next({ name: 'login' }); // 使用路由名称进行重定向  
    } else {
      next(); // 已经是登录页，直接通过  
    }
  } else {
    if (to.path == '/login') {
      next({ name: 'home' }); // 使用路由名称进行重定向  
    } else {
      next(); // 已经是登录页，直接通过  
    }
    next(); // 用户已登录，直接通过  
  }
});


export default router
